import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { ElNotification } from 'element-plus'

let stompClient = null

export const connectSocket = () => {
  const token = localStorage.getItem('token').token // 从 localStorage 获取 token
  if (!token) {
    console.error('No token found in localStorage')
    return
  }

  const socket = new SockJS('http://localhost:8080/ws-login') // 后端接口
  stompClient = Stomp.over(socket)

  // 连接时传递 token 作为连接头
  stompClient.connect(
    { token: token }, 
    () => {
      console.log('🟢 WebSocket 连接成功')

      // 订阅登录广播
      stompClient.subscribe('/topic/login', (message) => {
        const msg = message.body
        ElNotification({
          title: '用户登录通知',
          message: msg,
          position: 'bottom-right',
        })
      })
    },
    (error) => {
      console.error('WebSocket 连接失败:', error)
    }
  )
}